package com.example.mybatis.transaction.impl;

import com.example.mybatis.constant.TransactionIsolationLevel;
import com.example.mybatis.exception.MybatisException;
import com.example.mybatis.transaction.Transaction;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

public class ManageTransaction  implements Transaction {

   private final DataSource dataSource;

   private final TransactionIsolationLevel transactionIsolationLevel;

   private Connection connection;
    public ManageTransaction(DataSource dataSource, TransactionIsolationLevel transactionIsolationLevel) {
        this.dataSource = dataSource;
        this.transactionIsolationLevel = transactionIsolationLevel;
    }

    public ManageTransaction(DataSource dataSource) {
     this(dataSource,TransactionIsolationLevel.READ_COMMITTED);
    }

    @Override
    public Connection getConnection() {
       try {
           if (this.connection == null) {
               Connection connection = dataSource.getConnection();
               connection.setTransactionIsolation(transactionIsolationLevel.getLevel());
               this.connection = connection;
           }
           return connection;
       }catch (SQLException th){
           throw  new MybatisException(th);
       }
        //return null;
    }

    @Override
    public void commit() {

    }

    @Override
    public void rollback() {

    }
}
